import axios from "axios"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import getTempId from "./uuid"
import store from "../store"

NProgress.configure({ showSpinner: false })

const errorMessages = {
  401: "没有权限访问",
  403: "禁止访问",
  404: "资源找不到",
  500: "服务器故障",
}

const request = axios.create({
  baseURL: "/api",
  headers: {},
  timeout: 10000,
})

request.interceptors.request.use((config) => {
  config.headers.userTempId = getTempId()
  config.headers.token = store.state.login.token

  NProgress.start()
  return config
})

request.interceptors.response.use(
  (response) => {
    NProgress.done()
    if (response.data.code === 200) {
      return response.data.data
    }
    const message = response.data.message || "未知错误，请求管理员"
    // 功能失败，外面要触发catch
    alert(message)
    return Promise.reject(message)
  },
  (error) => {
    NProgress.done()
    console.dir(error)
    let message = "未知错误，请求管理员"

    if (error.response) {
      message = errorMessages[error.response.status]
    } else {
      if (error.message.indexOf("Network Error") > -1) {
        message = "网络断开链接，请打开网络链接试试"
      } else if (error.message.indexOf("timeout") > -1) {
        message = "网速太慢了，打开4G网或连接WIFI试试"
      }
    }

    alert(message)
    return Promise.reject(message)
  }
)

export default request
